package com.fingard.dsp.task.command;

import java.io.File;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.HashMap;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.fngrd01.util.StringHelper;
import com.fingard.dsp.bank.reqrespobj.ReqRespHeader;
import com.fingard.dsp.task.ITask;
import com.fingard.dsp.task.TaskBase;
import com.fingard.dsp.tcpserver.RequestNIO;
import com.fingard.net.WebRequest;

/**推送前置机状态*/
public class PushBankFrontStatus extends TaskBase implements ITask {

	private String logCode = "task"+File.separator+"PushBankFrontStatus";
	
	private static long polledCount = 0;//轮询次数
	public long getPolledCount(){
		return polledCount;
	}
	
	private static Date lastPolledTime;//最近轮询时间
	public Date getLastPolledTime(){
		return lastPolledTime;
	}
	
	/**pParams的key已转小写*/
	@Override
	public void execTask(HashMap<String, String> pParams) {
		try{
			lastPolledTime = new Date();
			polledCount++;
			FGBiz.logTrace.debug(logCode, logID + "\t开始执行前置机状态推送");
			String serverUrl = "";
			if(pParams.containsKey("serverurl")){
				serverUrl = pParams.get("serverurl");
			}
			if(StringHelper.isNullOrEmpty(serverUrl)){
				FGBiz.logTrace.error(logCode, logID + "\t未配置服务地址serverUrl参数值");
				return;
			}
			String directSys = "";
			if(pParams.containsKey("directsys")){
				directSys = pParams.get("directsys");
			}
			SocketChannel sk = null;
			RequestNIO bizO = new RequestNIO(sk, FGBiz.dspCenter.dspSet.encodingWithDspClient);
			ReqRespHeader tmpHeader = new ReqRespHeader();
			tmpHeader.transType = "GetBankFrontStatus";
			tmpHeader.transSeqID = logID+"";
			tmpHeader.transTime = Format.DateTimeFormat.format(new Date());
			String reqStr = "<ATSYH><TransReq><TransType>GetBankFrontStatus</TransType><TransSeqID>"+logID+"</TransSeqID><TransParam><DirectSys>"+directSys+"</DirectSys></TransParam></TransReq></ATSYH>";
			String retXml = FGBiz.dspCenter.getBankFrontStatus(bizO, tmpHeader, reqStr);
			
			FGBiz.logTrace.debug(logCode, logID + "\t获取过程中日志："+bizO.sbLog.toString());
			bizO.sbLog = new StringBuilder();
			
			FGBiz.logTrace.debug(logCode, logID + "\t推送报文："+retXml);
			FGBiz.logTrace.debug(logCode, logID + "\t推送地址："+serverUrl);
			
			WebRequest webReq = new WebRequest(serverUrl);
			webReq.setHttpTransmit();
			webReq.setLogCode(logCode);
			webReq.setSbLog(bizO.sbLog);
			byte[] sendBytes = retXml.getBytes("utf-8");
			String[] retStr = webReq.upload(sendBytes, "utf-8");
			if(bizO.sbLog.length()>0){
				FGBiz.logTrace.debug(logCode, logID + "\t推送过程中日志："+bizO.sbLog.toString());
			}
			
			FGBiz.logTrace.debug(logCode, logID + "\t得到的响应："+retStr[0]+"-"+retStr[1]);
			
		}catch(Throwable t){
			FGBiz.logTrace.exception(logCode, t, logID+"");
		}
	}

}
